package com.example.qrcodecamera;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccountManagementActivity extends AppCompatActivity {

    private ListView userListView;
    private ListView adminListView;
    private Button backButton;
    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_management_new);

        // 初始化数据库帮助类
        dbHelper = new DatabaseHelper(this);

        // 初始化视图
        userListView = findViewById(R.id.user_list_view);
        adminListView = findViewById(R.id.admin_list_view);
        backButton = findViewById(R.id.back_button);

        // 加载用户和管理员列表
        loadUserList();
        loadAdminList();

        // 设置用户列表项点击事件
        userListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> item = (HashMap<String, String>) parent.getItemAtPosition(position);
                showEditDialog("用户", item);
            }
        });

        // 设置管理员列表项点击事件
        adminListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> item = (HashMap<String, String>) parent.getItemAtPosition(position);
                showEditDialog("管理员", item);
            }
        });

        // 设置返回按钮点击事件
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 创建意图返回到登录页面
                Intent intent = new Intent(AccountManagementActivity.this, LoginActivity.class);
                startActivity(intent);
                finish(); // 结束当前页面
            }
        });
    }

    private void loadUserList() {
        List<UserAccount> users = dbHelper.getAllUsers();
        List<Map<String, String>> data = new ArrayList<>();

        for (int i = 0; i < users.size(); i++) {
            UserAccount user = users.get(i);
            Map<String, String> item = new HashMap<>();
            item.put("id", String.valueOf(i + 1));
            item.put("username", user.getUsername());
            item.put("password", user.getPassword());
            item.put("db_id", String.valueOf(user.getId())); // 保存数据库ID用于更新
            data.add(item);
        }

        // 创建表格样式的适配器
        SimpleAdapter adapter = new SimpleAdapter(
                this,
                data,
                R.layout.account_list_item,
                new String[]{"id", "username", "password"},
                new int[]{R.id.text_id, R.id.text_username, R.id.text_password}
        );

        userListView.setAdapter(adapter);
        
        if (users.isEmpty()) {
            Toast.makeText(this, "没有用户数据", Toast.LENGTH_SHORT).show();
        }
    }

    private void loadAdminList() {
        List<UserAccount> admins = dbHelper.getAllAdmins();
        List<Map<String, String>> data = new ArrayList<>();

        for (int i = 0; i < admins.size(); i++) {
            UserAccount admin = admins.get(i);
            Map<String, String> item = new HashMap<>();
            item.put("id", String.valueOf(i + 1));
            item.put("username", admin.getUsername());
            item.put("password", admin.getPassword());
            item.put("db_id", String.valueOf(admin.getId())); // 保存数据库ID用于更新
            data.add(item);
        }

        // 创建表格样式的适配器
        SimpleAdapter adapter = new SimpleAdapter(
                this,
                data,
                R.layout.account_list_item,
                new String[]{"id", "username", "password"},
                new int[]{R.id.text_id, R.id.text_username, R.id.text_password}
        );

        adminListView.setAdapter(adapter);
        
        if (admins.isEmpty()) {
            Toast.makeText(this, "没有管理员数据", Toast.LENGTH_SHORT).show();
        }
    }

    private void showEditDialog(final String type, final HashMap<String, String> item) {
        // 创建对话框布局
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_edit_account, null);
        
        // 获取对话框中的控件
        final EditText usernameEditText = dialogView.findViewById(R.id.edit_username);
        final EditText passwordEditText = dialogView.findViewById(R.id.edit_password);
        
        // 设置当前值
        usernameEditText.setText(item.get("username"));
        passwordEditText.setText(item.get("password"));
        
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改" + type + "账号")
               .setView(dialogView)
               .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       // 获取新的用户名和密码
                       String newUsername = usernameEditText.getText().toString().trim();
                       String newPassword = passwordEditText.getText().toString().trim();
                       
                       // 验证输入
                       if (newUsername.isEmpty() || newPassword.isEmpty()) {
                           Toast.makeText(AccountManagementActivity.this, 
                                   "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                           return;
                       }
                       
                       // 更新数据库
                       int dbId = Integer.parseInt(item.get("db_id"));
                       boolean success = false;
                       
                       if ("用户".equals(type)) {
                           success = dbHelper.updateUser(dbId, newUsername, newPassword);
                       } else if ("管理员".equals(type)) {
                           success = dbHelper.updateAdmin(dbId, newUsername, newPassword);
                       }
                       
                       if (success) {
                           Toast.makeText(AccountManagementActivity.this, 
                                   type + "账号已更新", Toast.LENGTH_SHORT).show();
                           // 刷新列表
                           if ("用户".equals(type)) {
                               loadUserList();
                           } else {
                               loadAdminList();
                           }
                       } else {
                           Toast.makeText(AccountManagementActivity.this, 
                                   "更新失败", Toast.LENGTH_SHORT).show();
                       }
                   }
               })
               .setNegativeButton("取消", null);
        
        builder.create().show();
    }
} 